'use strict';

const dataConst = require('../constant/data-const');
const Service = require('egg').Service;

class RecordService extends Service {
    async getLatestLoginDateSrv(userId) {
        const { app } = this;

        const result = await app.model.LoginRecord.findOne({
            where: {
                user_id: userId
            },
            attributes: ['updated_at'],
            order: [['updated_at', 'desc']]
        });

        if (result) {
            const { updated_at } = result;
            return updated_at;
        } else {
            return null;
        }
    }

    async recordLoginHistorySrv(userId, longitude, latitude) {
        const { app } = this;

        const [latestResult] = await app.model.LoginRecord.findAll({
            where: {
                user_id: userId
            },
            order: [['created_at', 'desc']],
            limit: 1,
            offset: 0
        });

        if (latestResult) {
            const { updated_at } = latestResult;
            const recordDate = new Date(updated_at).toLocaleDateString();
            const currentDate = new Date().toLocaleDateString();
            if (recordDate === currentDate) {
                latestResult.amount++;
                if (longitude && latitude) {
                    latestResult.longitude = longitude;
                    latestResult.latitude = latitude;
                }
                await latestResult.save();
                return false;
            } else {
                await app.model.LoginRecord.create({
                    user_id: userId,
                    longitude,
                    latitude
                });
                return true;
            }
        } else {
            await app.model.LoginRecord.create({
                user_id: userId,
                longitude,
                latitude
            });
            return true;
        }
    }

    async recordUserLookMemberSrv(userId, targetUserId) {
        const { app } = this;

        const [latestResult] = await app.model.LookRecord.findAll({
            where: {
                user_id: userId,
                target_user_id: targetUserId
            },
            order: [['created_at', 'desc']],
            limit: 1,
            offset: 0
        });

        if (latestResult) {
            const { updated_at } = latestResult;
            const recordDate = new Date(updated_at).toLocaleDateString();
            const currentDate = new Date().toLocaleDateString();
            if (recordDate === currentDate) {
                latestResult.amount++;
                return await latestResult.save();
            } else {
                return await app.model.LookRecord.create({
                    user_id: userId,
                    target_user_id: targetUserId
                });
            }
        } else {
            return await app.model.LookRecord.create({
                user_id: userId,
                target_user_id: targetUserId
            });
        }
    }

    async getLoginHistoryCountSrv(userId) {
        const { ctx } = this;

        let queryString =
            `select
                sum(amount) as count
                from tbl_login_record lr
                where true
                and lr.user_id = :userId`;

        const paramsData = {userId};

        const [result] = await ctx.helper.sqlQuery(queryString, paramsData);
        return result;
    }

    async getLoginLocationRecordSrv(longRegion, latRegion) {
        const { ctx } = this;

        const queryString =
            `select
                rcd.user_id, rcd.longitude, rcd.latitude, usr.nickname
                , concat(:serverUrl, :avatarPath, usr.id, '/', usr.avatar) as avatar_url
                , latest_time
                from (
                select
                max(updated_at) as latest_time
                from tbl_login_record
                group by user_id) ltr
                left join tbl_login_record rcd
                on ltr.latest_time = rcd.updated_at
                left join tbl_user usr
                on rcd.user_id = usr.id
                where true
                and rcd.longitude is not null
                and rcd.latitude is not null`;

        const paramsData = {
            serverUrl: dataConst.serverUrl,
            avatarPath: dataConst.avatarPath
        };

        return await ctx.helper.sqlQuery(queryString, paramsData);
    }
}

module.exports = RecordService;
